package com.sunshine.gateway.config;

import com.sunshine.gateway.util.JwtUtil;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 拦截器
 */

@Component
public class Interceptor implements GlobalFilter, Ordered {
    private static final Logger LOG = LoggerFactory.getLogger(Interceptor.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //后端接口拦截器拦截的请求
        String path = exchange.getRequest().getPath().value();
        // 排除不需要拦截的请求
        if (path.contains("/user/login/test")//测试接口
                || path.contains("/user/login/register")
                || path.contains("/user/login/login")
                || path.contains("/user/merchant/createMerchant")
                || path.contains("/user/merchant/loginMerchant")
                || path.contains("/home/products/someproducts")
                || path.contains("/home/products/bycategory")
        )
        {
            LOG.info("不需要验证:{}", path);
            return chain.filter(exchange);
        } else {
            LOG.info("需要验证:{}", path);
        }
        // 获取header的token参数
        String token = exchange.getRequest().getHeaders().getFirst("token");
        
        // 如果token为空，尝试从Authorization头获取
        if (token == null || token.isEmpty()) {
            String authHeader = exchange.getRequest().getHeaders().getFirst("Authorization");
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                token = authHeader.substring(7);
            }
        }
        
        LOG.info("会员登录验证开始，token：{}", token);
        if (token == null || token.isEmpty()) {
            LOG.info("token为空，请求被拦截");
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 设置响应头，告知前端具体的错误原因
            response.getHeaders().add("Error-Message", "TOKEN_MISSING");
            return response.setComplete();
        }
        // 校验token是否有效，包括token是否被改过，是否过期
        boolean validate = JwtUtil.validate(token);
        if (validate) {
            LOG.info("token有效，放行该请求");
            return chain.filter(exchange);
        } else {
            LOG.warn("token无效，请求被拦截");
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 设置响应头，告知前端具体的错误原因
            response.getHeaders().add("Error-Message", "TOKEN_INVALID_OR_EXPIRED");
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}